/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
export function csLeaf(i, j, w, first, maxfirst, prevleaf, ancestor) {
  var s, sparent; // our result

  var jleaf = 0;
  var q; // check j is a leaf

  if (i <= j || w[first + j] <= w[maxfirst + i]) {
    return -1;
  } // update max first[j] seen so far


  w[maxfirst + i] = w[first + j]; // jprev = previous leaf of ith subtree

  var jprev = w[prevleaf + i];
  w[prevleaf + i] = j; // check j is first or subsequent leaf

  if (jprev === -1) {
    // 1st leaf, q = root of ith subtree
    jleaf = 1;
    q = i;
  } else {
    // update jleaf
    jleaf = 2; // q = least common ancester (jprev,j)

    for (q = jprev; q !== w[ancestor + q]; q = w[ancestor + q]) {
      ;
    }

    for (s = jprev; s !== q; s = sparent) {
      // path compression
      sparent = w[ancestor + s];
      w[ancestor + s] = q;
    }
  }

  return {
    jleaf,
    q
  };
}